<template>
  <el-empty v-if="!currentMeter" description="请先选择表计" />
  <div v-else v-loading="loading" element-loading-text="loading..." class="meter-detail">
    <!-- 基础信息 -->
    <el-card shadow="never" class="box-card">
      <template #header>
        <span>基础信息</span>
        <DeviceEdit @refresh="handleRefresh" :currentMeter="currentMeter" :parent_meter="parent_meter"></DeviceEdit>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="表计名称">
          {{ currentMeter.meter_name || "未设置" }}
        </el-descriptions-item>
        <el-descriptions-item :label="getDisplayMeterIdLabel(currentMeter)">
          {{ getDisplayMeterId(currentMeter) }}
        </el-descriptions-item>
        <el-descriptions-item label="引擎">
          {{ getLabel(currentMeter.engine_id) || "未知" }}
        </el-descriptions-item>
        <el-descriptions-item label="规格">
          {{ currentMeter.specification || "未知" }}
        </el-descriptions-item>
        <el-descriptions-item label="制造商">
          {{ currentMeter.manufacturer || "未知" }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentMeter.status === 1 ? 'success' : 'danger'" effect="light">
            {{ currentMeter.status === 1 ? "可用" : "不可用" }}
          </el-tag>
        </el-descriptions-item>

      </el-descriptions>
    </el-card>

    <!-- 计量信息 -->
    <el-card shadow="never" class="box-card">
      <template #header>
        <div class="card-header">
          <span>计量信息</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="类型">
          {{
            currentMeter.type === 1
              ? "水表"
              : currentMeter.type === 2
                ? "电表"
                : currentMeter.type === 3
                  ? "气表"
                  : "压力表"
          }}
        </el-descriptions-item>
        <el-descriptions-item label="能源类别">
          {{ currentMeter.meter_type || "未知" }}
        </el-descriptions-item>
        <el-descriptions-item label="折标煤系数">
          {{ currentMeter.standard_coal_factor }}
        </el-descriptions-item>
        <el-descriptions-item label="倍率">
          {{ currentMeter.multiple || "1" }}
        </el-descriptions-item>
        <el-descriptions-item label="启表底数">
          {{ currentMeter.bottom_value || "0" }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentMeter.type === 1" label="参与漏水统计">
          <el-tag :type="currentMeter.is_drain_considerd ? 'success' : 'info'" effect="light">
            {{ currentMeter.is_drain_considerd ? "是" : "否" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="纳入离线统计">
          <el-tag :type="currentMeter.check_no_record ? 'success' : 'info'" effect="light">
            {{ currentMeter.check_no_record ? "是" : "否" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentMeter.type === 2" label="电表类型">
          <el-tag :type="getElecGenerateType(currentMeter.elec_generate).type" effect="light">
            {{ getElecGenerateType(currentMeter.elec_generate).label }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentMeter.type === 2 && currentMeter.elec_generate === 1" label="新能源类型">
          {{ currentMeter.new_energy || "未设置" }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentMeter.engine_id === 7" label="表计公式">
          {{ getFormulaNameById(currentMeter.meter_id) || "未知" }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 层级信息 -->
    <el-card shadow="never" class="box-card">
      <template #header>
        <div class="card-header">
          <span>层级信息</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="表计编码">
          {{ currentMeter.meter_code }}
        </el-descriptions-item>
        <el-descriptions-item label="父级表计">
          {{ getParentMeterName(currentMeter.parent_id) || "无" }}
        </el-descriptions-item>

      </el-descriptions>
    </el-card>

    <!-- 安装信息 -->
    <el-card shadow="never" class="box-card">
      <template #header>
        <div class="card-header">
          <span>安装信息</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="安装位置">
          {{ currentMeter.installation_location || "未知" }}
        </el-descriptions-item>
        <el-descriptions-item label="安装日期">
          {{ currentMeter.installation_date ? dayjs(currentMeter.installation_date).format("YYYY-MM-DD") : "未知" }}
        </el-descriptions-item>
        <el-descriptions-item label="供应点位">
          {{ currentMeter.supply_region || "未知" }}
        </el-descriptions-item>
        <el-descriptions-item label="区域">
          {{ useAreaStore().getAreaNameById(currentMeter.area_id) || "未知" }}
        </el-descriptions-item>
        <el-descriptions-item label="楼栋">
          {{ currentMeter.cell || "未知" }}
        </el-descriptions-item>
        <el-descriptions-item label="用途">
          {{ currentMeter.sub_category || "未知" }}
        </el-descriptions-item>
        <el-descriptions-item label="用能户">
          {{ getEnergyUserName(currentMeter.energy_user_id) || "未知" }}
        </el-descriptions-item>
        <el-descriptions-item label="重点设备">
          <el-tag :type="currentMeter.is_important_device ? 'warning' : 'info'" effect="light">
            {{ currentMeter.is_important_device ? "是" : "否" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentMeter.is_important_device" label="设备名称">
          {{ currentMeter.important_device_name || "未设置" }}
        </el-descriptions-item>
        <el-descriptions-item label="信号强度">
          {{ currentMeter.CSQ || "未知" }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 备注信息 -->
    <el-card shadow="never" class="box-card">
      <template #header>
        <div class="card-header">
          <span>备注信息</span>
        </div>
      </template>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="备注">
          {{ currentMeter.remarks || "无" }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>


</template>

<script setup>
import DeviceEdit from "./components/DeviceEdit.vue";
import { ref, computed, onMounted } from "vue";
import { useMeterStore } from "@/stores/meter";
import { getMeterInfoApi } from "@/api/meter";
import { useCompanyStore } from "@/stores/company";
import { useAreaStore } from "@/stores/area";
import { getFormulaList } from "@/utils/formula";
import { handleError } from "@/utils/handleError";
import { engineList } from "../../../../constants";
import dayjs from "dayjs";

const formulaList = ref([]);
const energyUserList = ref([]);

function getFormulaNameById(id) {
  const formula = formulaList.value.find((item) => item.id == id);
  return formula ? formula.name : "";
}

function getEnergyUserName(id) {
  if (!id) return "";
  const user = energyUserList.value.find(user => user.id === id);
  return user ? user.name : "";
}

function getParentMeterName(id) {
  if (!id || id === 0) return "无";
  const parentMeter = meterStore.meterList.find(meter => meter.id === Number(id));
  return parentMeter ? parentMeter.meter_code : "未知";
}

// 根据elec_generate值获取对应的标签类型和文本
function getElecGenerateType(value) {
  switch (Number(value)) {
    case 1:
      return { label: "发电", type: "success" };
    case 2:
      return { label: "售电", type: "primary" };
    case 3:
      return { label: "供电", type: "warning" };
    default:
      return { label: "未知", type: "info" };
  }
}

// 获取显示的标签（表计ID或公式名称或克隆表计）
function getDisplayMeterIdLabel(meter) {
  if (meter.engine_id === 7) {
    return "公式名称";
  } else if (meter.engine_id === 19) {
    return "克隆表计";
  }
  return "表计ID";
}

// 获取显示的值
function getDisplayMeterId(meter) {
  // 公式表：显示公式名称
  if (meter.engine_id === 7) {
    return getFormulaNameById(meter.meter_id) || "未知";
  }

  // 克隆虚拟表：显示原表计编码
  if (meter.engine_id === 19 && meter.meter_id) {
    const origin = meterStore.meterList.find(m => m.id === Number(meter.meter_id));
    return origin ? origin.meter_code : "未知";
  }

  // 其他表：显示表计ID
  return meter.meter_id || "未知";
}

const loading = ref(false);
const meterStore = useMeterStore();
const currentMeter = computed(() => meterStore.currentMeter);

const dialogVisible = ref(false);
const parent_meter = computed(() => ({
  id: currentMeter.value.parent_id,
  type: currentMeter.value.type,
}));

// 定义emit事件
const emit = defineEmits(["refresh", "meter-updated", "meter-deleted"]);

async function initCurrentMeter() {
  if (!meterStore.currentMeter) {
    if (!meterStore.treeDataForChart) {
      await meterStore.fetchMeterList();
      meterStore.setCurrentMeter(meterStore.treeDataForChart[0]);
    }
  }
}
initCurrentMeter();

function getLabel(id) {
  const item = engineList.find((item) => item.value === id);
  return item ? item.label : "";
}


function handleRefresh() {
  emit("refresh");
}


// 获取用能户列表
async function fetchEnergyUsers() {
  try {
    const { getEnergyUsersApi } = await import("@/api/energy_users");
    const res = await getEnergyUsersApi({
      company_id: useCompanyStore().currentCompany.id
    });
    energyUserList.value = res.data;
  } catch (error) {
    handleError(error, "获取用能户数据失败");
  }
}

onMounted(async () => {
  try {
    // 获取表计公式列表
    formulaList.value = await getFormulaList(
      useCompanyStore().currentCompany.id
    );

    // 获取用能户列表
    await fetchEnergyUsers();
  } catch (error) {
    handleError(error, "获取初始数据失败");
  }
});
</script>

<style scoped>
.meter-detail {
  display: flex;
  width: 100%;
  flex-direction: column;
  gap: 1rem;
}

.card-header {
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>